Java单元测试之 Apache CXF Restful

您所在的位置:网站首页 apache CXF REST SERVER是什么 Java单元测试之 Apache CXF Restful

Java单元测试之 Apache CXF Restful

2023-10-18 09:35| 来源: 网络整理| 查看: 265

Apache CXF框架的单元测试需要内置Jetty容器 org.eclipse.jetty jetty-webapp ${jetty.version} test 下面是一个基于Spring框架的Apache CXF测试示例

applicationContext-restful.xml

DemoRestful.java

@Path("demo") @Component("demoRestful") public class DemoRestful { @POST @Path("/test") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public String test(String str) { return "This is a cxf restful test method."; } }

DemoRestfulTest.java

@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = Application.class) public class DemoRestfulTest { public final String REST_SERVICE_URL = "http://localhost:8088/rest"; public final Server server = new Server(8088); @Before public void before() { // Register and map the dispatcher servlet final ServletHolder servletHolder = new ServletHolder(new CXFServlet()); final ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(servletHolder, "/rest/*"); context.addEventListener(new ContextLoaderListener()); context.setInitParameter( "contextConfigLocation", "classpath*:/applicationContext-restful.xml"); server.setHandler(context); try { server.start(); } catch (Exception e) { e.printStackTrace(); } } @After public void after() { try { server.stop(); } catch (Exception e) { e.printStackTrace(); } } @Test public void test() throws Exception { JSONObject json = new JSONObject(); json.put("name", "test"); WebClient client = WebClient.create(REST_SERVICE_URL); Response response = client.path("/demo/test") .accept("application/json") .type("application/json; ") .post(json.toJSONString()); Assert.assertEquals(response.getStatus(), 200); } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3